const Util = require("../../utils/util");

import {getComboProductList} from "../../api/product";

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    combo: {},
    cartTotal: {},
    selectCombo: {},
    currentIndex: 0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      id: options.id || "",
    })

    if (Util.isEmpty(this.data.id)) {
      app.Tips({title: "套餐编号错误",}, {tab: 3})
      return;
    }
    const that = this;

    Util.chekWxLogin().then(res => {
      let current_menu = wx.getStorageSync("current_menu");
      current_menu = Util.isEmpty(current_menu) ? null : JSON.parse(current_menu);
      that.setData({
        userInfo: res.userInfo,
        current_menu: current_menu,
      })

      if (Util.isEmpty(current_menu)) {
        let pages = getCurrentPages()
        if (pages.length > 1) {
          app.Tips({title: "菜单异常",}, {tab: 3})
        } else {
          app.Tips({title: "菜单异常",}, {tab: 1, url: "../index/index"})
        }
        return;
      }

      wx.showLoading({
        title: "正在加载..."
      })
      getComboProductList(this.data.id).then(res => {
        wx.hideLoading()
        that.setData({
          productList: res.data.productList || null,
          combo: res.data.combo || null,
          carts: Util.getCartList()
        })

        let carts = that.data.carts || {}
        if (!Util.isEmpty(carts)) { //多个套餐
          let currentIndex = that.data.currentIndex;

          for (const k in carts) {
            if (("combo_" + that.data.combo.id).indexOf(k) != false) {
              ++currentIndex;
            }
          }
          that.setData({
            currentIndex: currentIndex
          })
        }

        that.cartStat();
      }).catch(errmsg => {
        app.Tips({title: errmsg})
      })
    }).catch(errmsg => {
      app.Tips({title: errmsg})
    })

    this.onLoadTabbar();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  // 记录数据
  cartOptComboNew(e) {
    const that = this,
      combo = this.data.combo,
      productList = this.data.productList,
      key = e.currentTarget.dataset.key,
      type = parseInt(e.currentTarget.dataset.type);  // 1 : 增加  0： 减少

    if (Util.isEmpty(productList[key]))
      return;
    const product = productList[key],
      product_id = product.id

    let amount = 0;
    let selectCombo = this.data.selectCombo || {}
    if (Util.isEmpty(selectCombo[product_id])) {
      selectCombo[product_id] = {
        title: product.title,
        thumb: product.thumb || '',
        amount: 0,
        product_class: product.product_class   // 0： 不限 1: 荤 2： 素
      }
    } else {
      amount = selectCombo[product_id].amount || 0;
    }

    if (type == 1) {
      amount += 1;
    } else {
      amount -= 1;
    }
    amount = amount <= 0 ? 0 : amount;

    if (amount === 0) {
      delete selectCombo[product_id];
    } else {
      // 判断荤素 新增产品
      if (type == 1) {
        let hun_amount = 0, su_amount = 0, total_amount = 0;
        // 0： 不限 1: 荤 2： 素
        for (const k in selectCombo) {
          total_amount += selectCombo[k].amount;
          if (selectCombo[k].product_class == 1) {
            hun_amount += selectCombo[k].amount;
          } else if (selectCombo[k].product_class == 2) {
            su_amount += selectCombo[k].amount;
          }
        }
        //荤菜
        if (product.product_class == 1 && hun_amount >= combo.hun_amount) {
          app.Tips({
            title: "套餐最多能选" + combo.hun_amount + "种荤菜",
            hideMask: true,
          })
          return;
        }
        //素菜
        if (product.product_class == 2 && su_amount >= combo.su_amount) {
          app.Tips({
            title: "套餐最多能选" + combo.su_amount + "种素菜",
            hideMask: true,
          })
          return
        }
        if (total_amount > (combo.hun_amount + combo.su_amount)) {
          app.Tips({
            title: "套餐最多能选" + ((combo.hun_amount || 0) + (combo.su_amount || 0)) + "种素菜",
            hideMask: true,
          })
          return
        }
        selectCombo[product_id]['amount'] = amount;
      } else {
        selectCombo[product_id]['amount'] = amount;
      }
    }

    let carts = this.data.carts || {}
    if (amount > 0) {
      carts['combo_' + combo.id + '_' + this.data.currentIndex] = {
        title: combo.title,
        id: combo.id,
        thumb: combo.thumb || '/Uploads/default_combo.png',
        amount: 1,
        price: combo.price || 0.00,
        products: selectCombo
      }
    }
    this.setData({
      selectCombo: selectCombo,
      carts: carts
    })
    this.cartStat();
  },

  cartOptCombo(e) {
    const that = this,
      combo = this.data.combo,
      productList = this.data.productList,
      key = e.currentTarget.dataset.key,
      type = parseInt(e.currentTarget.dataset.type);  // 1 : 增加  0： 减少

    if (Util.isEmpty(productList[key]))
      return;

    const product = productList[key],
      product_id = product.id

    let carts = that.data.carts || {};
    if (Util.isEmpty(carts['combo_' + combo.id])) {//新增
      if (type === 1)
        carts['combo_' + combo.id] = {
          title: combo.title,
          id: combo.id,
          thumb: combo.thumb || '/Uploads/default_combo.png',
          amount: 1,
          price: combo.price || 0.00
        }
    }

    let amount = 0;
    let products = carts['combo_' + combo.id]['products'] || {} //套餐下面的长商品
    if (!Util.isEmpty(products[product_id])) {
      amount = products[product_id].amount || 0
    } else {
      products[product_id] = {
        title: product.title,
        thumb: product.thumb || '',
        amount: 0,
        product_class: product.product_class   // 0： 不限 1: 荤 2： 素
      }
    }

    if (type == 1) {
      amount += 1;
    } else {
      amount -= 1;
    }
    amount = amount <= 0 ? 0 : amount;

    if (amount == 0) {
      delete products[product_id];

      if (Util.isEmpty(products)) {
        delete carts['combo_' + combo.id];
      }
    } else {
      // 判断荤素 新增产品
      if (type == 1) {
        let hun_amount = 0, su_amount = 0, total_amount = 0;
        // 0： 不限 1: 荤 2： 素
        for (const k in products) {
          total_amount += products[k].amount;
          if (products[k].product_class == 1) {
            hun_amount += products[k].amount;
          } else if (products[k].product_class == 2) {
            su_amount += products[k].amount;
          }
        }

        //荤菜
        if (product.product_class == 1 && hun_amount >= combo.hun_amount) {
          app.Tips({
            title: "套餐最多能选" + combo.hun_amount + "种荤菜",
            hideMask: true,
          })
          return;
        }

        //素菜
        if (product.product_class == 2 && su_amount >= combo.su_amount) {
          app.Tips({
            title: "套餐最多能选" + combo.su_amount + "种素菜",
            hideMask: true,
          })
          return
        }

        if (total_amount > (combo.hun_amount + combo.su_amount)) {
          app.Tips({
            title: "套餐最多能选" + ((combo.hun_amount || 0) + (combo.su_amount || 0)) + "种素菜",
            hideMask: true,
          })
          return
        }
        products[product_id]['amount'] = amount;

      } else {
        products[product_id]['amount'] = amount;
      }
    }

    if (amount > 0) {
      carts['combo_' + combo.id]['products'] = products;
    }
    // carts['combo_' + combo.id]['products'] = products;
    // 查询购物车是否有值
    for (const k in carts) {
      if (Util.isEmpty(carts[k].products)) continue;
      for (const sk in carts[k].products) {
        if (carts[k].products[sk].amount == 0) {
          delete carts[k].products[sk];
        }
      }
      if (Util.isEmpty(carts[k].products)) {
        delete carts[k];
      }
    }

    that.setData({carts: carts})
    wx.setStorageSync("is_refresh", 1);
    wx.setStorageSync("carts", JSON.stringify(carts))

    this.cartStat();
  },

  goBack(e, type = 0) {
    const that = this,
      combo = this.data.combo

    let carts = that.data.carts || {};
    if (!Util.isEmpty(carts["combo_" + combo.id + "_" + this.data.currentIndex])) {
      let cart = carts["combo_" + combo.id + "_" + this.data.currentIndex]
      let hun_amount = 0,
        su_amount = 0;
      if (!Util.isEmpty(cart.products)) {
        for (const k in cart.products) {
          if (cart.products[k].product_class == 1) {
            hun_amount += cart.products[k].amount;
          } else {
            su_amount += cart.products[k].amount;
          }
        }
      }

      let diff_hun_amount = parseInt((combo.hun_amount || 0) - hun_amount),
        diff_su_amount = parseInt((combo.su_amount || 0) - su_amount);
      let msg = "";
      if (diff_hun_amount > 0) {
        msg += "荤菜还差" + diff_hun_amount + '份';
      }
      if (diff_su_amount > 0) {
        msg += " 素菜还差" + diff_su_amount + '份';
      }

      if (msg) {
        if (type == 1) { //顶部按钮
          delete carts['combo_' + combo.id + "_" + this.data.currentIndex];
          that.setData({carts: carts})
          wx.setStorageSync("is_refresh", 1);
          wx.setStorageSync("carts", JSON.stringify(carts))
        } else {
          app.Tips({title: msg, hideMask: true})
          return false;
        }
      }
    }

    if (type == 2) {
      return true;
    }
    wx.setStorageSync('carts', JSON.stringify(this.data.carts));
    wx.switchTab({
      url: "../index/index"
    })
  },

  cartStat() {
    const carts = this.data.carts;
    if (Util.isEmpty(carts)) {
      this.setData({
        cartTotal: {}
      })
      return;
    }

    let total_price = 0;
    for (const k in carts) {
      total_price += (carts[k].price || 0.0) * carts[k].amount
    }
    this.setData({
      cartTotal: {
        amount: Object.keys(carts).length,
        total_price: total_price.toFixed(2)
      }
    })

  },

  goCheckout(e) { //去结算
    if (Util.isEmpty(this.data.carts)) {
      Util.Tips({title: "至少选择一个上商品", hideMask: true})
      return;
    }

    const flag = this.goBack("", 2);
    if (!flag) return false;
    wx.setStorageSync('carts', JSON.stringify(this.data.carts));
    wx.redirectTo({
      url: "../cart/checkout"
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload(e) {
  },

  onLoadTabbar: function () {//底部tabbar返回数据
    const that = this

    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})

      wx.createSelectorQuery().in(that).select('.weui-footer')
        .boundingClientRect(function (rect) {
          if (!rect) return;
          let bottom = parseInt(rect.height);
          if (that.data.isIphoneX) {
            bottom += 24;
          } else {
            bottom += 15;
          }
          that.setData({
            bottom: bottom
          })
        }).exec()
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})